package com.unionftech.common.bean

import android.text.TextUtils
import com.unionftech.baselibrary.base.BaseApplication
import com.unionftech.common.R.string
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.utils.ToastUtils


data class ResponseResult<T>(
    var code: String, var msg: String? = "", var traceId: String? = "", var data: T? = null
) {
    companion object {
        const val SUCCESS_CODE = "MSCS0000"
        const val FAILED_CODE = "MSCS5000"

        /**
         * 此请求取消
         */
        const val CANCEL_CODE = "CANCEL10000"

        /**
         * 登录状态已过期
         */
        const val LOGIN_EXPIRED = "MSCS0008"

        /**
         * 登录在其他设备上登录
         */
        const val LOGIN_OTHER_DEVICES = "MSCS0007"

        /**
         * 网易易盾滑块验证
         */
        const val NETEASE_VERIFY = "MSUE3004"

        /**
         * 阿里云滑块验证
         */
        const val ALIYUN_VERIFY = "MSUE3005"


        @JvmStatic
        fun <T> buildSuccess(data: T?): ResponseResult<T?> {
            return ResponseResult(SUCCESS_CODE, "success", data = data)
        }

        @JvmStatic
        fun <T> buildFail(data: T? = null): ResponseResult<T?> {
            return ResponseResult(FAILED_CODE, "fail", data = data)
        }

        @JvmStatic
        fun <T> buildCancel(data: T? = null): ResponseResult<T?> {
            return ResponseResult(CANCEL_CODE, "", data = data)
        }
    }
}

fun ResponseResult<*>.toast(defaultString: String? = null) {
    if (ApiException.isTimeout(code)) {
        ToastUtils.longToast(
            DynamicResourceManager.getString(
                BaseApplication.appContext, string.timeout
            )
        )
        return
    }
    var errorMsg = DynamicResourceManager.getString(BaseApplication.appContext, this.code)
    if (TextUtils.isEmpty(errorMsg)) {
        errorMsg = defaultString ?: this.msg ?: this.code
    }
    ToastUtils.longToast(errorMsg)
}

fun ResponseResult<*>.toastTimeout() {
    if (ApiException.isTimeout(code)) {
        ToastUtils.longToast(
            DynamicResourceManager.getString(
                BaseApplication.appContext, string.timeout
            )
        )
    }

}